package com.sinog.core.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @desc 验证码工具类
 * @author lj
 * @date -
 */
@Slf4j
@Component
public class CaptchsUtil {

    private static final String SESSION_KEY = "captcha";

    /**
     * 调用生成验证码
     * @param request request
     * @param response response
     */
    public void out(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Captchas captchas = new Captchas();
        out(captchas,request,response);
    }

    /**
     * 生成验证码
     * @param captcha captcha
     * @param request request
     * @param response response
     */
    public void out(Captchas captcha,HttpServletRequest request,HttpServletResponse response) throws IOException {
        setHeader(response);
        request.getSession().setAttribute(SESSION_KEY,captcha.text().toLowerCase());
        log.info("存入的验证码==========================" + captcha.text());
        captcha.out(response.getOutputStream());
    }

    /**
     * 设置消息头
     * @param response response
     */
    public void setHeader(HttpServletResponse response) {
        response.setContentType("image/png");
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
    }
}